﻿using DllDependenciesAnalysis.AnalysisPlans;
using DllDependenciesAnalysis.Helpers;
using DllDependenciesAnalysis.Models;
using Newtonsoft.Json.Linq;
using NuGet.Common;
using NuGet.Packaging;
using NuGet.Repositories;
using NuGet.Versioning;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Xml.Linq;

namespace DllDependenciesAnalysis
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //var resolver = new VersionFolderPathResolver("packages");

            //var path1 = resolver.GetHashPath("Beisen.Cache", NuGetVersion.Parse("1.1.0.194"));
            //var path2 = resolver.GetManifestFilePath("Beisen.Cache", NuGetVersion.Parse("1.1.0.194"));
            //var path3 = resolver.GetPackageFilePath("Beisen.Cache", NuGetVersion.Parse("1.1.0.194"));




            //var versionListPath = resolver.GetVersionListPath("Beisen.Cache");

            //foreach (string item in Directory.EnumerateDirectories(versionListPath))
            //{
            //    var itemPath = item.Substring(versionListPath.Length).TrimStart(Path.DirectorySeparatorChar);

            //    NuGetVersion.TryParse(itemPath, out var  );
            //}

            //var id = "AutoMapper";

            //var PathResolver = new VersionFolderPathResolver("packages");

            //var _nuspecCache = new NuGet.Protocol.LocalNuspecCache();


            //ConcurrentDictionary<string, LocalPackageInfo> _packageCache = new ConcurrentDictionary<string, LocalPackageInfo>(PathUtility.GetStringComparerBasedOnOS());

            //List<LocalPackageInfo> list = new List<LocalPackageInfo>();
            //string versionListPath = PathResolver.GetVersionListPath(id);
            ////if (!Directory.Exists(versionListPath))
            ////{
            ////    return list;
            ////}

            //foreach (string item in Directory.EnumerateDirectories(versionListPath))
            //{
            //    if (!_packageCache.TryGetValue(item, out var value))
            //    {
            //        if (!NuGetVersion.TryParse(item.Substring(versionListPath.Length).TrimStart(Path.DirectorySeparatorChar), out var version))
            //        {
            //            continue;
            //        }

            //        if (File.Exists(PathResolver.GetHashPath(id, version)))
            //        {
            //            string manifestFilePath = PathResolver.GetManifestFilePath(id, version);
            //            string packageFilePath = PathResolver.GetPackageFilePath(id, version);
            //            Lazy<NuspecReader> orAdd = _nuspecCache.GetOrAdd(manifestFilePath, item);
            //            value = new LocalPackageInfo(id, version, item, manifestFilePath, packageFilePath, orAdd);
            //            _packageCache.TryAdd(item, value);
            //        }
            //    }

            //    if (value != null)
            //    {
            //        list.Add(value);
            //    }

            //    var files = value.Nuspec.GetContentFiles();

            //    var packageTypes = value.Nuspec.GetPackageTypes();

            //    var refGroups = value.Nuspec.GetReferenceGroups();
            //    var dependencyGroups = value.Nuspec.GetDependencyGroups();
            //}


            try
            {
                var result = CommandLine.Parser.Default.ParseArguments<UserInput>(args);
                if (result.Errors?.Any() == true)
                {
                    foreach (var error in result.Errors)
                    {
                        //Console.WriteLine(error);
                    }


                    var allPlans = AnalysisPlanManager.Instance.GetAllAnalysisPlans();
                    if (allPlans?.Any() == true)
                    {
                        Console.WriteLine($"目前已经支持的解析器");
                        foreach (var item in allPlans)
                        {
                            Console.WriteLine(item.Name);
                        }
                    }

                    return;
                }

                var planName = result.Value.Action;
                var path = result.Value.Path;
                var searchPath = result.Value.SearchPaths?.ToList() ?? new List<string>();

                var systemPath = "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.5";
                if (searchPath.Contains(systemPath) != true)
                    searchPath.Add(systemPath);

                var plan = AnalysisPlanManager.Instance.GetAnalysisPlan(planName);
                if (plan == null)
                {
                    Console.WriteLine($"无法根据{planName}找到对应的解析器");
                    return;
                }

                plan.Analysis(new AnalysisContent
                {
                    Path = path,
                    SearchPaths = searchPath,
                });

                Console.WriteLine("Finsh");
            }
            finally
            {
                //Thread.Sleep(TimeSpan.FromSeconds(5));
            }
        }
    }
}
